const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();
const app = getApp()

Page({
  data: {
    showInfo: {
      daily: {
        title: '我的日常',
        text: '分享日常生活，为你推荐爱好类似的朋友',
        placeholder: '例：云吸猫，爱读张爱玲'
      },
      wish: {
        title: '我的愿望',
        text: '分享日常生活，为你推荐爱好类似的朋友',
        placeholder: '例：找一个人，一起打switch'
      }
    },
    type: 'daily',  // 问题分类
    manner: '',  // 新增还是编辑
    index: null, // 问题下标
    content: ''
  },
  
  onLoad(options) {
    const { type, index, manner } = options;
    this.setData({ type, index, manner });
    const key = this.data.type + 's';
    this.setData({
      content: app.globalData.userInfo[key][index]
    });
  },
  bindInputChange(e) {
    this.setData({
      content: e.detail.value
    });
  },
  sure() {
    if (!this.data.content) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    this._save();
  },
  async _save() {
    let params = {};
    if (this.data.type === 'daily') {
      let dailys = app.globalData.userInfo.dailys || [];
      (dailys.length <= 0 || this.data.manner === 'add') ? dailys.push(this.data.content) : dailys[this.data.index] = this.data.content;
      params.daily = dailys.join('|~|~');
    }
    if (this.data.type === 'wish') {
      let wishs = app.globalData.userInfo.wishs;
      (wishs.length <= 0 || this.data.manner === 'add') ? wishs.push(this.data.content) : wishs[this.data.index] = this.data.content;
      params.wish = wishs.join('|~|~');
    }
    const { returnCode = null, bean = {} } = await request({
      url: api.editUser,
      method: 'put',
      data: params
    });
    if (returnCode === '0000') {
      wx.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 1000,
        success: () => {
          wx.navigateBack({
            delta: 1
          });
        }
      });
    }
  },
  
})
